//index.js

const app = getApp();

Page({
  data: {
    lessThan: '<',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    latitude:0,
    longitude:0,
    page: 1,
    pre_page : 0,
    orderList:[],
    noMoreData : false,
    showMessage : false,
    positionIsEmpty : false,
    position:'',
    imagePath : '',
    voiceImage : '',
    toPlay : '',
    isPlay : false,
    isToMapReload : false
  },
  
  onLoad: function () {
    
    var that = this;

    // 设置全局图片路径
    this.setData({
      imagePath: app.globalData.imagePath,
      voiceImage: app.globalData.imagePath + "/send_voice.png",
      staticApiUrl: app.globalData.staticApiUrl
    });

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      });
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      };
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          });
        }
      });

    }

    // 初始化录音
    app.initRecorderManager();
    // 音频自然播放结束事件
    app.data.innerAudioContext.onEnded((res) => {
      that.setData({
        toPlay: '',
        isPlay: false
      });
    });

  },
  onShow : function() {
    // 如果没有设置位置，将重新获取位置
    if (!app.globalData.position && 1 == app.globalData.reload_position) {
      app.getUserPosition();
    }

    var page = false;
    if (this.data.orderList.length > 0 && this.data.page > 1) {
        page = true;
    }

    if (app.globalData.position) {
      this.setData({
        position: app.globalData.position,
      });
      // 获取订单列表
      if (this.data.page != this.data.pre_page && this.data.isToMapReload == false) {
        this.getOrderList(page);
      }
    } else if (this.data.canIUse) {
      app.positionReadyCallback = lo => {
        this.setData({
          position: lo.position
        });

        app.globalData.latitude = lo.latitude;
        app.globalData.longitude = lo.longitude;

        // 获取订单列表
        if (this.data.page != this.data.pre_page) {
          this.getOrderList(page);
        }
      }
    }

    if (this.data.position == '' && app.globalData.position == '') {
      this.setData({
        // positionIsEmpty: true
      });
    }

  }
  /**
   * 页面隐藏
   */
  ,onHide : function() {
    // 如果正在播放，跳转页面是停止播放
    if (this.data.isPlay) {
      app.data.innerAudioContext.stop();

      this.setData({
        toPlay: ''
      });
    }
  }
  /**
   * 打开地图选择位置
   */
  , toMap: function (e) {
    
    app.formIdSubmit(e);

    var that = this;
    that.data.isToMapReload = true;

    wx.chooseLocation({
      success: res => {
        app.globalData.latitude = res.latitude;
        app.globalData.longitude = res.longitude;
        app.globalData.position = res.name;
        
        that.setData({
          position: res.name,
        });

        that.data.page = 1;
        that.setData({
          orderList: []
        });
        that.getOrderList();
        that.data.isToMapReload = false;
      },
      fail: res => {
        app.reportError(res.errMsg, 'index-toMap-wx.chooseLocation');
        app.checkAuthUserLocation();
      }
    });
  }
  /**
   * 去发布页面
   */
  , toAction: function (e) {

    app.formIdSubmit(e);

    app.checkAuthUserInfo('/pages/toAction/toAction');
  }

  ,getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
  /**
   * 获取拼单列表
   */
  , getOrderList: function (paged = false) {
    var that = this;
    
    wx.showLoading({
      title: '加载中',
    });
    
    wx.request({
      url: app.globalData.apiUrl+'index/list',
      header: {
        'content-type': 'application/json',
        "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
      },
      data : {
        page:that.data.page,
        lat : app.globalData.latitude,
        lon: app.globalData.longitude
      },
      success: function (res) {
        if (res.data.code == 10000 && res.data.message.length > 0) {
          let order_list = [];
          if (paged) {
            order_list = that.data.orderList.concat(res.data.message);
          } else {
            order_list = res.data.message;
          }
          that.setData({
            orderList: order_list,
            showMessage: false
          });
        } else {
          that.data.page = that.data.page - 1;
        }

        /**
         * 当没有拼单信息是，显示提示信息
         */
        if (that.data.orderList.length <= 0) {
          that.setData({
            showMessage: true
          });
        }

        wx.stopPullDownRefresh();
        wx.hideLoading();

        if (res.data.code == 10000 && res.data.message.length == 0 && that.data.orderList.length > 0) {
          wx.showToast({
            title: '别拉了，真的没有了',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail : function(res) {
        app.reportError(res.errMsg, 'index-getOrderList-index/list');
        wx.hideLoading();
      }
    });
  },
  toDetail: function(e) {
    app.formIdSubmit(e);
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/detail/detail?id='+id,
    });
  },
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
    this.data.page = 1;
    this.setData({
      orderList: []
    });
    this.getOrderList();
  }
  /**
   * 下拉触发
   */
  ,onReachBottom:function() {
    if (!this.data.noMoreData) {
      this.data.page = this.data.page + 1;
    }

    this.data.pre_page = this.data.page;
    
    this.getOrderList(true);
  },
  /**
   * 语音播放
   */
  playRecord : function(e) {

    var description_voice = app.globalData.staticVoiceUrl + e.currentTarget.dataset.key;
    if (description_voice == '') {
      app.tip("请先录音！")
      return;
    }

    app.data.innerAudioContext.src = description_voice;
    app.data.innerAudioContext.play();

    this.setData({
      toPlay: e.currentTarget.dataset.key,
      isPlay: true
    });
  },
  /**
   * 停止播放
   */
  stopPlayRecord: function() {

    app.data.innerAudioContext.stop();

    this.setData({
      toPlay: '',
      isPlay:false
    });
  }
})
